var events = {};

function on(name, self, callback) {
	var tuple = [self, callback];
	var callbacks = events[name];
	if (Array.isArray(callbacks)) {
		callbacks.push(tuple);
	}else {
		events[name] = [tuple];
	}
}

function remove(name, self) {
	var callbacks = events[name];
	if (Array.isArray(callbacks)) {
		events[name] = callbacks.filter((tuple) => {
			return tuple[0] != self;
		})
	}
}

function emit(name, data) {
	var callbacks = events[name];
	if (Array.isArray(callbacks)) {
		callbacks.map((tuple) => {
			var self = tuple[0];
			var callback = tuple[1];
			callback.call(self, data);
		})
	}
}

function arrToObj(obj) {
    var arr = []
    for (let i in obj) {
        for(let key in obj[i]){
            arr[key] = obj[i][key];
        }
    }
    return arr;
}
function objToArr(obj) {
    var arr = []
    for (let i in obj) {
        let o = {};
        o[i] = obj[i];
        arr.push(o)
    }
    return arr;
}
function arrayToJson(o) {
    var r = [];
    if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
    if (typeof o == "object") {
      if (!o.sort) {
        for (var i in o)
          r.push(i + ":" + arrayToJson(o[i]));
        if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
          r.push("toString:" + o.toString.toString());
        }
        r = "{" + r.join() + "}";
      } else {
        for (var i = 0; i < o.length; i++) {
          r.push(arrayToJson(o[i]));
        }
        r = "[" + r.join() + "]";
      }
      return r;
    }
    return o.toString();
  }

function getQueryString(url, name) {
    var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i');
    var r = url.substr(1).match(reg);

    if (r != null) {
        return r[2]
    }
    return null;
}
function timestampToTime(timestamp) {
        var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        var D = date.getDate() < 10 ? '0'+date.getDate() + ' ' : date.getDate() + ' ';
        var h = date.getHours() + ':';
        var m = date.getMinutes();
        var s = date.getSeconds();
        return M+D+h+m;
}

export default {
  on:on,
  remove:remove,
  emit:emit,
  arrToObj:arrToObj,
  objToArr:objToArr,
  getQueryString:getQueryString,
  timestampToTime:timestampToTime
}
// exports.on = on;
// exports.remove = remove;
// exports.emit = emit;